﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RabitPart.ReadApi;

namespace RabitPart.WritedPartApi.Controllers
{
    /// <summary>
    /// 七牛云图片
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PhotographPartController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<PhotographPartController> logger;
        private readonly QiniuUtils _photographResponstity;
        public PhotographPartController(IMediator mediator, ILogger<PhotographPartController> logger, QiniuUtils _photographResponstity)
        {
            this.mediator = mediator;
            this.logger = logger;
            this._photographResponstity = _photographResponstity;
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("UploadFile")]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            //校验文件是否为空
            if (file.Length == 0)
            {
                return BadRequest("文件为空");
            }

            //生成文件保存名称
            string name = DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(file.FileName);

            //使用MemoryStream保存文件
            using (var stream = new MemoryStream())
            {
                file.CopyTo(stream);
                byte[] data = stream.ToArray();

                //调用mediator上传图片
                try
                {
                    _photographResponstity.UploadFile(data, name);
                }
                catch (Exception ex)
                {
                    // 捕获上传异常并返回错误信息
                    return StatusCode(500, $"文件上传失败: {ex.Message}");
                    throw;
                }

            }

            return Ok("文件上传成功");
        }


    }
}
